﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ScrollRectControl : MonoBehaviour, IEndDragHandler, IBeginDragHandler
{
    public static ScrollRectControl Instance;

    public Scrollbar bar;
    public GameObject item;
    public GameObject content;
    public int gameFlow;
    public ArrayList gameFlowArray;
    public bool isStop = false;
    public TextInfo textInfo;
    public GameObject gameEnd;
    public List<GameObject> dialogList;

    public List<TextInfo> restartList;

    private float _textTime = 0f;
    private ScrollRect _scrollRect;
    private LayoutElement _itemLayoutElement;

    private bool isScroll = true;

     void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        _scrollRect = transform.GetComponent<ScrollRect>();
        _itemLayoutElement = item.GetComponent<LayoutElement>();
        gameFlow = 4;
        restartList = new List<TextInfo>();
        gameFlowArray = new ArrayList();
        dialogList = new List<GameObject>();

        //PlayerPrefs.DeleteAll();

        if (PlayerPrefs.HasKey("GameFlow"))
        {
            int[] temp = PlayerPrefsX.GetIntArray("GameFlow");
            for (int i = 0; i < temp.Length; i++)
            {
                gameFlowArray.Add(temp[i]);
            }
            PlayerComeBack(PlayerPrefsX.GetIntArray("GameFlow"));
        }
    }

    void Update()
    {
        _textTime += Time.deltaTime;
        
        if (_textTime >= 1.5f && !isStop)
        {
            isScroll = true;
            addItem();
            _textTime = 0f;
            bar.value = 0;
            //if (dialogList.Count >= 20)
            //{
            //    ItemControl item = content.transform.GetChild(0).GetComponent<ItemControl>();
            //    item.DestroyGO();
            //}
        }

        if (isScroll && bar.value >= 0)
            bar.value = 0;
    }

    public void OnBeginDrag(PointerEventData data)
    {
        isScroll = false;
    }

    public void OnEndDrag(PointerEventData data)
    {
        //if (bar.value >= 1)
        //{
        //    //先拿到数据再说 
        //    if (PlayerPrefs.HasKey("GameFlow"))
        //    {
        //        int[] temp = PlayerPrefsX.GetIntArray("GameFlow");
        //        for (int i = 0; i < temp.Length; i++)
        //        {
        //            gameFlowArray.Add(temp[i]);
        //        }
        //    }
        //    //获取他的下标，如果下标小于4，就不要继续了，还刷新什么
        //    ItemControl itm = content.transform.GetChild(0).GetComponent<ItemControl>();
        //    RectTransform rectPos = itm.transform.GetComponent< RectTransform>();
        //    int index = gameFlowArray.IndexOf(itm._textInfo.id);
        //    if (index <= 1)
        //        return;

        //    //从下标开始读取
        //    int[] ary = (int[])gameFlowArray.ToArray(typeof(int));

        //    for (int i = index - 1; i >= index - 15; i--)
        //    {
        //        if (i <=0) 
        //            return; 

        //        //开始生成，并且不影响主流循环
        //        TextInfo t = ReadXml._instance.GetContentById(ary[i]);
        //        print(ary[i]);
        //        GameObject newItem = addChild(item, content);
        //        newItem.SetActive(true);
        //        dialogList.Add(newItem);
        //        SetGridHeight(1);
        //        //设置内容
        //        ItemControl ic = newItem.GetComponent<ItemControl>();
        //        ic.setItem(t);
        //        if (t.itemType == 2)
        //        {
        //            string str = "playerChoose" + t.id.ToString();
        //            int chooseKey = PlayerPrefs.GetInt(str);
        //            if (chooseKey == 1)
        //            {
        //                ic.LeftChoose();
        //            }
        //            else if (chooseKey == 2)
        //            {
        //                ic.RightChoose();
        //            }
        //            else
        //            {
        //                Debug.Log("并没有选择");
        //            }
        //        }
        //        newItem.transform.GetComponent<RectTransform>().anchoredPosition = new Vector2(rectPos.rect.x, rectPos.rect.y + 60);
        //        print(rectPos.rect.x + "  " + rectPos.rect.y + " + 60");
        //    }
        //    //所有子物体进行排序，并且到进度条到最上面.
        //    bar.value = 0.99f;
        //}

    }


    //添加的时候调用这个方法。
    void addItem()
    {
        //生成一个信息
        textInfo = ReadXml._instance.GetContentById(gameFlow);

        //记录重生点
        if (textInfo.restart > 0)
        {
            restartList.Add(textInfo);
        }

        //下一个信息没有内容，则游戏结束
        //if (textInfo.text1 == "0")
        //{
        //    TheEnd();
        //}

        //游戏流程继续
        //gameFlowArray.Add(PlayerPrefsX.GetIntArray("GameFlow"));

        gameFlowArray.Add(gameFlow);
        print(gameFlow);
        gameFlow++;
        int[] ary = (int[])gameFlowArray.ToArray(typeof(int));
        PlayerPrefsX.SetIntArray("GameFlow", ary);
        GameObject newItem = addChild(item, content);
        newItem.SetActive(true);
        dialogList.Add(newItem);
        SetGridHeight(1);
        newItem.GetComponent<ItemControl>().setItem(textInfo);
    }


    //添加，并且设置父类，大小，位置。
    GameObject addChild(GameObject o, GameObject parent)
    {
        if (o == null || parent == null)
        {
            return null;
        }
        GameObject inst = GameObject.Instantiate(o) as GameObject;
        inst.transform.SetParent(parent.transform, false);
        inst.transform.localPosition = Vector3.zero;
        inst.transform.localScale = Vector3.one;
        return inst;
    }

    void RemoveItem(int num)
    {
        Destroy(content.transform.GetChild(num));
    }

    //设置Content的高度
    void SetGridHeight(int num)
    {
        VerticalLayoutGroup VerticalLG = content.GetComponent<VerticalLayoutGroup>();

        float childCount = content.transform.childCount;

        float height = ((childCount + num - 1) / num) * _itemLayoutElement.preferredHeight + 3.0f;
        //height += (((childCount + num - 1) / num) - 1) * g.spacing.y;
        content.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
    }

    //游戏结束
    public void TheEnd()
    {
        Time.timeScale = 0;
        GameEnd end = gameEnd.GetComponent<GameEnd>();
        gameEnd.SetActive(true);
    }

    //游戏如果有进度，那么游戏从进度点开始走
    public void PlayerComeBack(int[] intArr)
    {
        TextInfo isGo = null;
        foreach (int i in intArr)
        {
            //生成一个信息
            TextInfo ti = ReadXml._instance.GetContentById(i);
            //记录重生点
            if (ti.restart > 0)
            {
                restartList.Add(ti);
            }
            //创建GO,设置高度
            GameObject newItem = addChild(item, content);
            newItem.SetActive(true);
            SetGridHeight(1);

            //设置内容
            ItemControl ic = newItem.GetComponent<ItemControl>();
            ic.setItem(ti);
            if (ti.itemType == 2)
            {
                string str = "playerChoose" + ti.id.ToString();
                int chooseKey = PlayerPrefs.GetInt(str);
                if (chooseKey == 1)
                {
                    ic.LeftChoose();
                }
                else if (chooseKey == 2)
                {
                    ic.RightChoose();
                }
                else
                {
                    Debug.Log("并没有选择");
                }
            }
            isGo = ti;
        }
        //print(intArr.Length+"  "+isGo.id);
        if (isGo.itemType == 2)
        {
            gameFlow = intArr[intArr.Length - 1]+1;
            isStop = true;
        }
        else
        {
            gameFlow = intArr[intArr.Length - 1]+1;
            isStop = false;
        }
        bar.value = 1;
    }
}